import { ref } from 'vue'

interface LocationInfo {
  latitude: number
  longitude: number
}

export function useLocation(
  intervalMs = 5000,
  onSuccess?: (loc: LocationInfo) => void
) {
  const location = ref<LocationInfo>({ latitude: 0, longitude: 0 })
  const error = ref<string | null>(null)

  let watchId: number | null = null
  let intervalId: number | null = null

  const updateLocation = () => {
    // #ifdef H5
    console.log('h5---run--')
    if (!navigator.geolocation) {
      console.log('当前浏览器不支持定位')
      error.value = '当前浏览器不支持定位'
      return
    }

    watchId = navigator.geolocation.watchPosition(
      pos => {
        const loc = {
          latitude: pos.coords.latitude,
          longitude: pos.coords.longitude,
        }
        location.value = loc
        console.log('---h5onSuccess', location.value)
        onSuccess && onSuccess(loc)
      },
      err => {
        error.value = err.message
        console.log('---h5error', error.value)
      },
      {
        enableHighAccuracy: false,
        maximumAge: 1000,
        timeout: 10000,
      }
    )
    // #endif

    // #ifndef H5
    intervalId = setInterval(() => {
      uni.getLocation({
        type: 'wgs84', // 或 'gcj02'
        success: (res: UniApp.GetLocationSuccess) => {
          const loc = {
            latitude: res.latitude,
            longitude: res.longitude,
          }
          location.value = loc
          onSuccess && onSuccess(loc)
        },
        fail: (err: UniApp.GeneralCallbackResult) => {
          error.value = err.errMsg
        },
      })
    }, intervalMs) as unknown as number
    // #endif
  }

  const stop = () => {
    // #ifdef H5
    if (watchId !== null) {
      navigator.geolocation.clearWatch(watchId)
      watchId = null
    }
    // #endif

    // #ifndef H5
    if (intervalId !== null) {
      clearInterval(intervalId)
      intervalId = null
    }
    // #endif
  }

  // 返回函数而不直接在 useLocation 中调用生命周期钩子
  return {
    location,
    error,
    stop,
    updateLocation, // 让父组件触发此函数
  }
}
